//
//  currentWorkSetManager.m
//  dataGathering
//
//  Created by apple on 14/11/17.
//  Copyright (c) 2014年 shuili. All rights reserved.
//

#import "currentWorkSetManager.h"
#import "spatialite_t.h"
#import "LatestLayerListModel.h"
#import "NSDate+toFormattedString.h"
#import "LatestLayerModelManager.h"


@interface currentWorkSetManager()
@property(nonatomic, retain)NSMutableDictionary *workSetDict;
@property(nonatomic, retain)FMDatabase *fmDB;
@property(nonatomic, retain)LocalLayerListModel *localLayerListModel;
@property(nonatomic, retain)NSString *appDocumentPath;
@property(nonatomic, retain)LocalFeatureModel *featureModel;
@end
@implementation currentWorkSetManager
static currentWorkSetManager *sharedManager=nil;

workSet *currentWorkSetEntity;

- (NSString*)dateToLocalDateString :(NSString*)dateString
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyyMMddHHmmss"];
    
    NSDate *localUpdateDate = [dateFormatter dateFromString:dateString];
    
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *tranlateeString = [dateFormatter stringFromDate:localUpdateDate];
    return [tranlateeString mutableCopy];
}

-(LocalFeatureModel*)getLocalFeatureModel
{
    return _featureModel;
}

-(void)checkTablesExistInWorkset{
    FMResultSet *rsCheckWorksetTable = [_fmDB executeQuery:@"select count(*) from sqlite_master where type = 'table' and name='workset_table'"];
    if([rsCheckWorksetTable next]){
        int n = [rsCheckWorksetTable intForColumnIndex:0];
        if(n == 0){
            [_fmDB executeUpdate:DATABASECMD_WORKSETLIST_CREATE];
        }
        [rsCheckWorksetTable close];
    }
    
    FMResultSet *rsCheckLayerTable= [_fmDB executeQuery:@"select count(*) from sqlite_master where type = 'table' and name='layer_info_table'"];
    if([rsCheckLayerTable next]){
        int n = [rsCheckLayerTable intForColumnIndex:0];
        if(n == 0){
            [_fmDB executeUpdate:DATABASECMD_LAYERINFOTABLE_CREATE];
        }
        [rsCheckLayerTable close];
    }
    

}

-(void)updateLayerStatusUsingFetchedLayerMode :(LatestLayerListModel*)model
{
    if(model){
        [_fmDB executeUpdate:@"DELETE FROM layer_info_table"];
        for(GroupModel* group in [[model feature] groups])
        {
            for (LayerModel *layer in [group layers])
            {
                NSString *layername = [NSString stringWithFormat:@"%@.%@",[group name],[layer name]];
                NSString *layerversion = [NSString stringWithFormat:@"%d",[layer version]];
                [_fmDB executeUpdate:@"INSERT OR REPLACE INTO layer_info_table(name, type, renderer, version) VALUES (?,?,?,?)",layername,[layer type],@"",layerversion];
            }
        }
    }
}

-(void)loadLocalLayerListModel
 {
     _featureModel = [[LocalFeatureModel alloc] init];
     _featureModel.groups = [[NSMutableArray alloc] initWithCapacity:10];
     
     FMResultSet *loadLayerRS = [_fmDB executeQuery:@"SELECT * FROM layer_info_table"];
     while([loadLayerRS next]){
         BOOL found = NO;
         NSString *layername = [loadLayerRS stringForColumn:@"name"];
         NSArray *aArray = [layername componentsSeparatedByString:@"."];
         NSString *layertype = [loadLayerRS stringForColumn:@"type"];
         NSString *layerrenderer = [loadLayerRS stringForColumn:@"renderer"];
         NSString *layerversion = [loadLayerRS stringForColumn:@"version"];
         LocalLayerModel *newlayer = [[LocalLayerModel alloc] init];
         newlayer.name = [aArray objectAtIndex:1];
         newlayer.type = layertype;
         newlayer.version = [layerversion intValue];
         newlayer.renderer = layerrenderer;
         
         for (LocalGroupModel *group in _featureModel.groups)
         {
             if([group.name isEqualToString:[aArray objectAtIndex:0]]){
                 [group.layers addObject:newlayer];
                 found = YES;
                 break;
             }
         }
         if(!found){
             LocalGroupModel *newgroup = [[LocalGroupModel alloc] init];
             newgroup.layers = [[NSMutableArray alloc] initWithCapacity:10];
             newgroup.name = [aArray objectAtIndex:0];
             [newgroup.layers addObject:newlayer];
             [_featureModel.groups addObject:newgroup];
         }
     }
     [loadLayerRS close];
 }

-(void)initWorksetDict
{
    
    int err;
    _appDocumentPath = [NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    
    NSString* json = @"{\"feature\": {\"groups\": [{\"name\": \"水利公共类\",\"icon\": \"icon1\",\"layers\": [{\"name\": \"流域边界\",\"icon\": \"icon1\",\"url\": \"liuyubianjie.com\",\"version\": \"1\"},{\"name\": \"河流\",\"icon\": \"icon2\",\"url\": \"heliu.com\",\"version\": \"1\"}]},{\"name\": \"水利工程\",\"icon\": \"icon2\",\"layers\": [{\"name\": \"堤防\",\"icon\": \"icon2\",\"url\": \"differing.com\",\"version\": \"1\"}]}]},\"map\": {\"groups\": [{\"name\": \"江苏省\",\"version\": \"2\",\"layers\": [{\"name\": \"影像切片\",\"icon\": \"icon3\",\"url\": \"jiangsuyingxiang.com\"},{\"name\": \"矢量切片\",\"icon\": \"icon4\",\"url\": \"jiangsushiliang.com\"}]},{\"name\": \"南京市\",\"version\": \"4\",\"layers\": [{\"name\": \"影像切片\",\"icon\": \"icon5\",\"url\": \"nanjingyingxiang.com\"},{\"name\": \"矢量切片\",\"icon\": \"icon6\",\"url\": \"nanjingshiliang.com\"}]}]}}";
    NSError* nserr = nil;
    LatestLayerListModel* layerListModel = [[LatestLayerListModel alloc] initWithString:json error:&nserr];
    NSLog(@"error is %@",[nserr localizedDescription]);
    NSLog(@"1st group name is %@", [((GroupModel*)[[[layerListModel feature] groups] objectAtIndex:0]) name]);
    
    NSString* dbpath = [_appDocumentPath stringByAppendingPathComponent:@"workset.sqlite"];
    spatialite_init(0);

    err = sqlite3_open_v2([dbpath UTF8String], &_db, SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, NULL);
    sqlite3_enable_load_extension(_db, 1);

    _fmDB = [FMDatabase databaseWithPath:dbpath];
    [_fmDB setDB:_db :dbpath];

    NSLog(@"db path is %@", dbpath);
    
    if(err != SQLITE_OK) {
        NSLog(@"error opening!: %d", err);
        return;
    }
    
    [self checkTablesExistInWorkset];
    if([[AFNetworkReachabilityManager sharedManager] isReachable]){
        
        //[[LatestLayerModelManager sharedInstance] getLatestLayerModel]
        
        [self updateLayerStatusUsingFetchedLayerMode:[[LatestLayerModelManager sharedInstance] getLatestLayerModel]];
    }
    [self loadLocalLayerListModel];
    
    
    FMResultSet *rs1 = [_fmDB executeQuery:@"SELECT * FROM workset_table"];
    if(![rs1 next]){
        NSLog(@"workset_table is empty");
        [rs1 close];

        [_fmDB executeUpdate:DATABASECMD_INSERT_NEW_WORKSET,[[NSUUID UUID] UUIDString],@"工作集1",(NSString*)[[NSUserDefaults standardUserDefaults] objectForKey:@"username"], nil, @"2014-12-31", @"2014-12-31",@"鼓楼区北京西路", @"工作集1的描述", @"", [NSNumber numberWithBool:false], [NSNumber numberWithBool:false], [NSNumber numberWithBool:false],[NSNumber numberWithBool:false]];
        
        [_fmDB executeUpdate:@"INSERT INTO layer_info_table(name, type, renderer, version) VALUES (?,?,?,?)",@"水利公共类.河流",@"POLYGON",@"",@"1"];

        NSString* testCollectedDataPath = [_appDocumentPath stringByAppendingPathComponent:@"1.sqlite"];
        spatialite_init(0);
        sqlite3 *testDB;
        sqlite3_open_v2([testCollectedDataPath UTF8String], &testDB, SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, NULL);
        sqlite3_enable_load_extension(testDB, 1);
        //spatialite_init_ex(testDB, testptr, YES);
        sqlite3_close_v2(testDB);

        
    }

    _workSetDict = [[NSMutableDictionary alloc] initWithCapacity:10];
    FMResultSet *rs4 = [_fmDB executeQuery:DATABASECMD_GET_ALL_WORKSET];
    while ([rs4 next]) {
        NSString *name = [rs4 stringForColumn:@"name"];
        NSString *creator = [rs4 stringForColumn:@"user"];
        //NSString *imageurl = [rs4 stringForColumn:@"ImageURL"];
        NSString *createtime = [rs4 stringForColumn:@"time_create"];
        NSString *updateTime = [rs4 stringForColumn:@"time_update"];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyyMMddHHmmss"];
        
        NSDate *localCreateDate = [dateFormatter dateFromString:createtime];
        if(localCreateDate){
            [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
            createtime = [dateFormatter stringFromDate:localCreateDate];
        }
        [dateFormatter setDateFormat:@"yyyyMMddHHmmss"];
        NSDate *localUpdateDate = [dateFormatter dateFromString:updateTime];
        if(localUpdateDate){
            [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
            updateTime = [dateFormatter stringFromDate:localUpdateDate];
        }
        
        
        NSString *locationString = [rs4 stringForColumn:@"location_name"];
        NSString *worksetDescription = [rs4 stringForColumn:@"description"];
        NSString *worksetID = [rs4 stringForColumn:@"id"];
        //double worksetX = [rs4 doubleForColumn:@"x"];
        //double worksetY = [rs4 doubleForColumn:@"y"];
        BOOL isAutoSync = [rs4 boolForColumn:@"isAutoSync"];
        BOOL isCompleted = [rs4 boolForColumn:@"isFinished"];
        BOOL isTracking = [rs4 boolForColumn:@"isLocationTracked"];
        BOOL isOnlineLayerDisplayed = [rs4 boolForColumn:@"isOnlineLayerDisplayed"];
        BOOL isDeleted = [rs4 boolForColumn:@"isDeleted"];
        workSet *newworkset = [[workSet alloc] initWithNameAndDesc:name :worksetDescription];
        [newworkset setCreator:creator];
        [newworkset setImageURL:nil];
        [newworkset setCreateTime:createtime];
        [newworkset setUpdateTime:updateTime];
        [newworkset setLocationString:locationString];
        [newworkset setWorksetID:worksetID];
        [newworkset setX:0.0];
        [newworkset setY:0.0];
        [newworkset setIsAutoSync:isAutoSync];
        [newworkset setIsCompleted:isCompleted];
        [newworkset setIsTracking:isTracking];
        [newworkset setIsOnlineLayerDisplayed:isOnlineLayerDisplayed];
        [newworkset setIsDeleted:isDeleted];
        
        NSString *dataDBPath = [NSString stringWithFormat:@"%@.sqlite",name];
        NSString* collectedDatabasePath = [_appDocumentPath stringByAppendingPathComponent:dataDBPath];
        FMDatabase *dataFMDB = [FMDatabase databaseWithPath:collectedDatabasePath];
        [dataFMDB open];
        
        FMResultSet *rsLayers = [_fmDB executeQuery:@"select * from layer_info_table"];
        while([rsLayers next]){
            NSString *layername = [rsLayers stringForColumn:@"name"];
            NSString *version = [rsLayers stringForColumn:@"version"];
            
            NSString *layerTableName = [NSString stringWithFormat:@"%@",layername];
            NSString *layerMediaTableName = [NSString stringWithFormat:@"%@_media",layername];
            
            //NSString *queryLayerTable = [NSString stringWithFormat:@"select OBJECTID,name,description,time_create,time_update,user_name,user_realname,geometry as geometryText from '%@'",layerTableName];
            NSString *queryLayerTable = [NSString stringWithFormat:@"select OBJECTID,name,description,time_create,time_update,user_name,user_realname,AsText(geometry) as geometryText from '%@'",layerTableName];
            FMResultSet *rs5 = [dataFMDB executeQuery:queryLayerTable];
            while([rs5 next]){
                NSString *Dataname = [rs5 stringForColumn:@"name"];
                NSString *DataDescription = [rs5 stringForColumn:@"description"];
                NSString *CreatedUserName = [rs5 stringForColumn:@"user_name"];
                NSString *CreatedRealName = [rs5 stringForColumn:@"user_realname"];
                NSString *CreatedTime = [rs5 stringForColumn:@"time_create"];
                NSString *udpatedTime = [rs5 stringForColumn:@"time_update"];
                NSString* IdNumber = [rs5 stringForColumn:@"OBJECTID"];
                //const void *blob = [rs5 spatialDataForColumn:@"geometryText"];
                int size = [rs5 spatialDataSizeForColumn:@"geometryText"];
                NSString* geometryText = [rs5 stringForColumn:@"geometryText"];
                AGSGeometry *geometry = [AGSGeometryParse TextToGeometry:geometryText];
                
                //AGSGeometry *geometry = [self AGSGeometryWithSpatialiteWKB_gaia:blob size:size];

                NSMutableArray *imagelist = [[NSMutableArray alloc] initWithCapacity:10];
                NSMutableArray *imageNamelist = [[NSMutableArray alloc] initWithCapacity:10];
                NSString *queryLayerMediaTable = [NSString stringWithFormat:@"select * from '%@' where OBJECTID = '%@'",layerMediaTableName,IdNumber];
                FMResultSet *rs6 = [dataFMDB executeQuery:queryLayerMediaTable];
                while([rs6 next]){
                    if([[rs6 stringForColumn:@"type"] isEqualToString:@"jpg"]){
                        NSString *imageName = [rs6 stringForColumn:@"media"];
                        UIImage *perImage = [UIImage imageWithContentsOfFile:[[_appDocumentPath stringByAppendingString:@"/"] stringByAppendingString:imageName]];
                        if(perImage){
                            [imagelist addObject:perImage];
                            
                            [imageNamelist addObject:imageName];
                        }
                    }

                }
                [rs6 close];
                NSArray *aArray = [layername componentsSeparatedByString:@"."];
                collectedData *newdata = [[collectedData alloc] initWithAllAttr:Dataname :DataDescription :IdNumber :CreatedUserName :CreatedRealName :CreatedTime :udpatedTime :imagelist :geometry :[aArray objectAtIndex:0] :[aArray objectAtIndex:1]];
                [newdata setImageNameList:imageNamelist];
                [newworkset addNewCollectedData:newdata];
            }
        }
        [rsLayers close];
        [_workSetDict setObject:newworkset forKey:name];

    }
    [rs4 close];
}

-(void)reloadWorksetInfo
{
    [_workSetDict removeAllObjects];
    _workSetDict = [[NSMutableDictionary alloc] initWithCapacity:10];
    FMResultSet *rs4 = [_fmDB executeQuery:DATABASECMD_GET_ALL_WORKSET];
    while ([rs4 next]) {
        NSString *name = [rs4 stringForColumn:@"name"];
        NSString *creator = [rs4 stringForColumn:@"user"];
        //NSString *imageurl = [rs4 stringForColumn:@"ImageURL"];
        NSString *createtime = [rs4 stringForColumn:@"time_create"];
        NSString *updateTime = [rs4 stringForColumn:@"time_update"];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyyMMddHHmmss"];
        
        NSDate *localCreateDate = [dateFormatter dateFromString:createtime];
        if(localCreateDate){
            [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
            createtime = [dateFormatter stringFromDate:localCreateDate];
        }
        [dateFormatter setDateFormat:@"yyyyMMddHHmmss"];
        NSDate *localUpdateDate = [dateFormatter dateFromString:updateTime];
        if(localUpdateDate){
            [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
            updateTime = [dateFormatter stringFromDate:localUpdateDate];
        }
        
        
        NSString *locationString = [rs4 stringForColumn:@"location_name"];
        NSString *worksetDescription = [rs4 stringForColumn:@"description"];
        NSString *worksetID = [rs4 stringForColumn:@"id"];
        //double worksetX = [rs4 doubleForColumn:@"x"];
        //double worksetY = [rs4 doubleForColumn:@"y"];
        BOOL isAutoSync = [rs4 boolForColumn:@"isAutoSync"];
        BOOL isCompleted = [rs4 boolForColumn:@"isFinished"];
        BOOL isTracking = [rs4 boolForColumn:@"isLocationTracked"];
        BOOL isOnlineLayerDisplayed = [rs4 boolForColumn:@"isOnlineLayerDisplayed"];
        BOOL isDeleted = [rs4 boolForColumn:@"isDeleted"];
        workSet *newworkset = [[workSet alloc] initWithNameAndDesc:name :worksetDescription];
        [newworkset setCreator:creator];
        [newworkset setImageURL:nil];
        [newworkset setCreateTime:createtime];
        [newworkset setUpdateTime:updateTime];
        [newworkset setLocationString:locationString];
        [newworkset setWorksetID:worksetID];
        [newworkset setX:0.0];
        [newworkset setY:0.0];
        [newworkset setIsAutoSync:isAutoSync];
        [newworkset setIsCompleted:isCompleted];
        [newworkset setIsTracking:isTracking];
        [newworkset setIsOnlineLayerDisplayed:isOnlineLayerDisplayed];
        [newworkset setIsDeleted:isDeleted];
        
        NSString *dataDBPath = [NSString stringWithFormat:@"%@.sqlite",name];
        NSString* collectedDatabasePath = [_appDocumentPath stringByAppendingPathComponent:dataDBPath];
        FMDatabase *dataFMDB = [FMDatabase databaseWithPath:collectedDatabasePath];
        [dataFMDB open];
        
        FMResultSet *rsLayers = [_fmDB executeQuery:@"select * from layer_info_table"];
        while([rsLayers next]){
            NSString *layername = [rsLayers stringForColumn:@"name"];
            NSString *version = [rsLayers stringForColumn:@"version"];
            
            NSString *layerTableName = [NSString stringWithFormat:@"%@",layername];
            NSString *layerMediaTableName = [NSString stringWithFormat:@"%@_media",layername];
            
            //NSString *queryLayerTable = [NSString stringWithFormat:@"select OBJECTID,name,description,time_create,time_update,user_name,user_realname,geometry as geometryText from '%@'",layerTableName];
            NSString *queryLayerTable = [NSString stringWithFormat:@"select OBJECTID,name,description,time_create,time_update,user_name,user_realname,AsText(geometry) as geometryText from '%@'",layerTableName];
            FMResultSet *rs5 = [dataFMDB executeQuery:queryLayerTable];
            while([rs5 next]){
                NSString *Dataname = [rs5 stringForColumn:@"name"];
                NSString *DataDescription = [rs5 stringForColumn:@"description"];
                NSString *CreatedUserName = [rs5 stringForColumn:@"user_name"];
                NSString *CreatedRealName = [rs5 stringForColumn:@"user_realname"];
                NSString *CreatedTime = [rs5 stringForColumn:@"time_create"];
                NSString *udpatedTime = [rs5 stringForColumn:@"time_update"];
                NSString* IdNumber = [rs5 stringForColumn:@"OBJECTID"];
                //const void *blob = [rs5 spatialDataForColumn:@"geometryText"];
                int size = [rs5 spatialDataSizeForColumn:@"geometryText"];
                NSString* geometryText = [rs5 stringForColumn:@"geometryText"];
                AGSGeometry *geometry = [AGSGeometryParse TextToGeometry:geometryText];
                
                //AGSGeometry *geometry = [self AGSGeometryWithSpatialiteWKB_gaia:blob size:size];
                
                NSMutableArray *imagelist = [[NSMutableArray alloc] initWithCapacity:10];
                NSMutableArray *imageNamelist = [[NSMutableArray alloc] initWithCapacity:10];
                NSString *queryLayerMediaTable = [NSString stringWithFormat:@"select * from '%@' where OBJECTID = '%@'",layerMediaTableName,IdNumber];
                FMResultSet *rs6 = [dataFMDB executeQuery:queryLayerMediaTable];
                while([rs6 next]){
                    if([[rs6 stringForColumn:@"type"] isEqualToString:@"jpg"]){
                        NSString *imageName = [rs6 stringForColumn:@"media"];
                        UIImage *perImage = [UIImage imageWithContentsOfFile:[[_appDocumentPath stringByAppendingString:@"/"] stringByAppendingString:imageName]];
                        if(perImage){
                            [imagelist addObject:perImage];
                            
                            [imageNamelist addObject:imageName];
                        }
                    }
                    
                }
                [rs6 close];
                NSArray *aArray = [layername componentsSeparatedByString:@"."];
                collectedData *newdata = [[collectedData alloc] initWithAllAttr:Dataname :DataDescription :IdNumber :CreatedUserName :CreatedRealName :CreatedTime :udpatedTime :imagelist :geometry :[aArray objectAtIndex:0] :[aArray objectAtIndex:1]];
                [newdata setImageNameList:imageNamelist];
                [newworkset addNewCollectedData:newdata];
            }
        }
        [rsLayers close];
        [_workSetDict setObject:newworkset forKey:name];
        
    }
    [rs4 close];

}

-(id)init
{
    self = [super init];
    if (self) {
       [self initWorksetDict];
    }
    return self;
}

+(currentWorkSetManager *)sharedInstance{
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        sharedManager=[[currentWorkSetManager alloc] init];
        currentWorkSetEntity = NULL;
        
    });
    return sharedManager;
}

-(BOOL)addNewWorkset:(NSString *)name :(NSString *)description
{
    if([_workSetDict objectForKey:name]){
        return NO;
    }
    workSet *newWorkSet = [[workSet alloc] initWithNameAndDescAndUser:name :description :(NSString*)[[NSUserDefaults standardUserDefaults] objectForKey:@"username"]];
    [newWorkSet setCreateTime:[[NSDate date] toFormattedString]];
    [newWorkSet setUpdateTime:[[NSDate date] toFormattedString]];
    
    NSString *worksetUUID = [[NSUUID UUID] UUIDString];
    
    [_fmDB executeUpdate:DATABASECMD_INSERT_NEW_WORKSET,worksetUUID,name,(NSString*)[[NSUserDefaults standardUserDefaults] objectForKey:@"username"], nil, [[NSDate date] toFormattedString], [[NSDate date] toFormattedString],@"", description, @"", [NSNumber numberWithBool:false], [NSNumber numberWithBool:false], [NSNumber numberWithBool:false], [NSNumber numberWithBool:false]];
    
    
    

    
    FMResultSet *rs = [_fmDB executeQuery:@"select id from workset_table where name = ?",name];
    while([rs next]){
        [newWorkSet setWorksetID:worksetUUID];
        [_workSetDict setObject:newWorkSet forKey:name];
        NSString *dataDBPath = [NSString stringWithFormat:@"%@.sqlite",name];
        NSString* collectedDatabasePath = [_appDocumentPath stringByAppendingPathComponent:dataDBPath];
        spatialite_init (0);

        sqlite3 *db;
        
        sqlite3_open_v2([collectedDatabasePath UTF8String], &db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL);
        sqlite3_enable_load_extension(db, 1);
        //spatialite_init_ex(_db, ptr, YES);
        FMDatabase *dataFMDB = [FMDatabase databaseWithPath:collectedDatabasePath];
        [dataFMDB setDB:db :collectedDatabasePath];
        FMResultSet * testrs = [dataFMDB executeQuery:@"select InitSpatialMetaData(1)"];
        while([testrs next]){
            int tt = [testrs intForColumnIndex:0];
            NSLog(@"result of init spaitalite index is %d",tt);
        }
        [dataFMDB close];
        [dataFMDB open];
        
        
        FMResultSet *rsLoopForLayers = [_fmDB executeQuery:@"select name, version from layer_info_table"];
        while([rsLoopForLayers next]){
            NSString *layername = [rsLoopForLayers stringForColumn:@"name"];
            NSString *layerversion = [rsLoopForLayers stringForColumn:@"version"];
            NSString *createCollectedDataQuery = [NSString stringWithFormat:DATABASECMD_NEWCOLLECTEDDATA_DATABASE_CREATE,layername];
            NSString *createCollectedDataGeoColumnQuery = [NSString stringWithFormat:DATABASECMD_NEWCOLLECTEDDATA_DATABASE_ADDGEOMETRYCOLUMN,layername];
            NSString *createCollectedDataMedioaQuery = [NSString stringWithFormat:DATABASECMD_NEWCOLLECTEDDATA_MEDIA_DATABASE_CREATE,layername];
            [dataFMDB executeUpdate:createCollectedDataQuery];
            
            FMResultSet *addGeoColumnRS = [dataFMDB executeQuery:createCollectedDataGeoColumnQuery];
            while([addGeoColumnRS next]){
                
            }
            [dataFMDB executeUpdate:createCollectedDataMedioaQuery];
            
        }
        [rsLoopForLayers close];
        [dataFMDB close];
        
    }
    [rs close];
    
    return YES;
}



-(NSArray*)getWorksetArray
{
    if([_workSetDict count] > 0){
        return [_workSetDict allValues];
    } else {
        return nil;
    }
}

-(workSet*)getCurrentWorkSet{
    if(currentWorkSetEntity){
        return currentWorkSetEntity;
    } else {
        return nil;
    }
}

-(void)setCurrentWorkSet :(NSString*)name
{
    if([_workSetDict count] > 0){
        currentWorkSetEntity = [_workSetDict objectForKey:name];
    }
}

-(void)updateCurrentWorkSet :(workSet*)editedWorkset
{
    if([_workSetDict count] > 0){
        workSet *workset = [_workSetDict objectForKey:currentWorkSetEntity.name];
        [workset updateDescWithNewWorkset:editedWorkset];
        [_workSetDict removeObjectForKey:currentWorkSetEntity.name];
        [_workSetDict setObject:workset forKey:editedWorkset.name];
    }
}

-(void)markWorksetToDelete
{
    [currentWorkSetEntity setIsDeleted:YES];
    [_fmDB executeUpdate:@"UPDATE workset_table SET isDeleted = ? WHERE name = ?",[NSNumber numberWithBool:YES],[currentWorkSetEntity name]];
}

-(void)deleteCurrentWorkSet
{
    [_workSetDict removeObjectForKey:[currentWorkSetEntity name]];
    [_fmDB executeUpdate:@"DELETE FROM workset_table WHERE name = ?",[currentWorkSetEntity name]];
    
    NSString *dataDBName = [NSString stringWithFormat:@"%@.sqlite",[currentWorkSetEntity name]];
    NSString* datadbpath = [_appDocumentPath stringByAppendingPathComponent:dataDBName];
    
    if([[NSFileManager defaultManager] fileExistsAtPath:datadbpath]){
        NSError *error;
        [[NSFileManager defaultManager] removeItemAtPath:datadbpath error:&error];
    }
}

-(void)confirmDeleteWorkSet: (workSet*)worksetToDelete
{
    [_workSetDict removeObjectForKey:[worksetToDelete name]];
    [_fmDB executeUpdate:@"DELETE FROM workset_table WHERE id = ?",[worksetToDelete worksetID]];
    
    NSString *dataDBName = [NSString stringWithFormat:@"%@.sqlite",[worksetToDelete name]];
    NSString* datadbpath = [_appDocumentPath stringByAppendingPathComponent:dataDBName];
    
    if([[NSFileManager defaultManager] fileExistsAtPath:datadbpath]){
        NSError *error;
        [[NSFileManager defaultManager] removeItemAtPath:datadbpath error:&error];
    }
}

-(BOOL)updateWorksetNameAndDesc :(NSString*)worksetName :(NSString*)worksetDesc
{

    if([_workSetDict count] > 0){
        NSString *previousName = [NSString stringWithFormat:@"%@", currentWorkSetEntity.name];
        workSet *workset = [_workSetDict objectForKey:currentWorkSetEntity.name];
        [workset setWorksetDescription:worksetDesc];
        [_workSetDict removeObjectForKey:currentWorkSetEntity.name];
        [workset setName:worksetName];
        [workset setUpdateTime:[[NSDate date] toFormattedString]];
        [_workSetDict setObject:workset forKey:worksetName];
        
        //if(![_db executeUpdate:@"UPDATE worksetlist SET Name = ? WHERE Name = ?",worksetName,currentWorkSetEntity.name]){
           // NSLog(@"error is %@",[_db lastErrorMessage]);
        //}
        [_fmDB executeUpdate:@"UPDATE workset_table SET description = ?,time_update = ? WHERE name = ?",worksetDesc,[[NSDate date] toFormattedString],previousName];
        
        if(![_fmDB executeUpdate:@"UPDATE workset_table SET name = ? WHERE name = ?",worksetName,previousName]){
            // NSLog(@"error is %@",[_db lastErrorMessage]);
        }
        
    }
    return YES;
}

-(void)updateIsAutoSync :(NSString*)worksetName :(BOOL)isAutoSync
{
    [_fmDB executeUpdate:@"UPDATE workset_table SET isAutoSync = ? WHERE name = ?",[NSNumber numberWithBool:isAutoSync],worksetName];
    [_fmDB executeUpdate:@"UPDATE workset_table SET time_update = ? WHERE name = ?",[[NSDate date] toFormattedString],[currentWorkSetEntity name]];
    [currentWorkSetEntity setIsAutoSync:isAutoSync];
    [currentWorkSetEntity setUpdateTime:[[NSDate date] toFormattedString]];
}

-(void)updateIsTracking :(NSString*)worksetName :(BOOL)isTracking
{
    [_fmDB executeUpdate:@"UPDATE workset_table SET isLocationTracked = ? WHERE name = ?",[NSNumber numberWithBool:isTracking],worksetName];
    [_fmDB executeUpdate:@"UPDATE workset_table SET time_update = ? WHERE name = ?",[[NSDate date] toFormattedString],[currentWorkSetEntity name]];
    [currentWorkSetEntity setIsTracking:isTracking];
    [currentWorkSetEntity setUpdateTime:[[NSDate date] toFormattedString]];
}

-(void)updateIsOnlineLayerDisplayed :(NSString*)worksetName :(BOOL)isOnlineLayerDisplayed
{
    [_fmDB executeUpdate:@"UPDATE workset_table SET isOnlineLayerDisplayed = ? WHERE name = ?",[NSNumber numberWithBool:isOnlineLayerDisplayed],worksetName];
    [_fmDB executeUpdate:@"UPDATE workset_table SET time_update = ? WHERE name = ?",[[NSDate date] toFormattedString],[currentWorkSetEntity name]];
    [currentWorkSetEntity setIsOnlineLayerDisplayed:isOnlineLayerDisplayed];
    [currentWorkSetEntity setUpdateTime:[[NSDate date] toFormattedString]];
}

-(void)updateIsCompleted :(NSString*)worksetName :(BOOL)isCompleted
{
    [_fmDB executeUpdate:@"UPDATE workset_table SET isFinished = ? WHERE name = ?",[NSNumber numberWithBool:isCompleted],worksetName];
    
    [_fmDB executeUpdate:@"UPDATE workset_table SET time_update = ? WHERE name = ?",[[NSDate date] toFormattedString],[currentWorkSetEntity name]];
    [currentWorkSetEntity setIsCompleted:isCompleted];
    [currentWorkSetEntity setUpdateTime:[[NSDate date] toFormattedString]];

}

-(void)addCollectedData :(NSString*)worksetName :(collectedData*)newdata
{
    
    NSString *dataDBName = [NSString stringWithFormat:@"%@.sqlite",worksetName];
    NSString* datadbpath = [_appDocumentPath stringByAppendingPathComponent:dataDBName];
    
    FMDatabase *dataFMDB = [FMDatabase databaseWithPath:datadbpath];
    [dataFMDB open];
    
    NSString *dataTableName = [NSString stringWithFormat:@"%@.%@",[newdata mainType],[newdata type]];
    //NSString *insertNewDataQuery = [NSString stringWithFormat:DATABASECMD_INSERT_NEW_COLLECTEDDATA,dataTableName];
    NSString *newID = [[NSUUID UUID] UUIDString];
    [newdata setIdNumber:newID];
    NSString *insertNewDataQuery = [NSString stringWithFormat:@"INSERT INTO '%@'(OBJECTID, id, name, description, time_create, time_update, user_name, user_realname, geometry) VALUES ('%@','0','%@','%@','%@','%@','%@','%@',GeomFromText('%@',4490))",dataTableName,newID,[newdata name],[newdata dataDescription],[[NSDate date] toFormattedString],[[NSDate date] toFormattedString],[newdata createdUserName],[newdata createdRealName],[AGSGeometryParse GeometryToWKT:newdata]];
    char *err_msg = NULL;
    sqlite3_exec([dataFMDB sqliteHandle], [insertNewDataQuery UTF8String], NULL, NULL, &err_msg);
    NSLog(@"%s",err_msg);
    
    //[dataFMDB executeUpdate:insertNewDataQuery,[[NSUUID UUID] UUIDString], [NSNumber numberWithInteger:0],[newdata name],[newdata dataDescription],[newdata createdTime],[newdata createdTime],[newdata createdUserName],[newdata createdRealName], [AGSGeometryParse GeometryToWKT:newdata]];
    
   
    for(UIImage *image in [newdata imageList]){
        
        NSString *imageUUID = [[NSUUID UUID] UUIDString];
        
        NSString *insertNewDataQuery = [NSString stringWithFormat:@"INSERT INTO '%@_media'(OBJECTID, media, type) VALUES ('%@','%@','%@')",dataTableName,newID,imageUUID,@"image"];
        [dataFMDB executeUpdate:insertNewDataQuery];
        
        NSData *imagedata=UIImageJPEGRepresentation(image,1);
        NSString *imagePath = [NSString stringWithFormat:@"/%@.jpg",imageUUID];
        [[NSFileManager defaultManager] createFileAtPath:[_appDocumentPath stringByAppendingString:imagePath] contents:imagedata attributes:nil];
    }
    
    [dataFMDB close];
    
    [_fmDB executeUpdate:@"UPDATE workset_table SET time_update = ? WHERE name = ?",[[NSDate date] toFormattedString],[currentWorkSetEntity name]];
    [currentWorkSetEntity setUpdateTime:[[NSDate date] toFormattedString]];
    
}

-(void)forkCollectedData :(collectedData*)newdata
{
    
    NSString *dataDBName = [NSString stringWithFormat:@"%@.sqlite",[currentWorkSetEntity name]];
    NSString* datadbpath = [_appDocumentPath stringByAppendingPathComponent:dataDBName];
    
    FMDatabase *dataFMDB = [FMDatabase databaseWithPath:datadbpath];
    [dataFMDB open];
    
    NSString *dataTableName = [NSString stringWithFormat:@"%@.%@",[newdata mainType],[newdata type]];
    
    /*check if corresponding table already exists*/
    FMResultSet *validateTableRS = [dataFMDB executeQuery:@"select count(*) from sqlite_master where type = 'table' and name='?'",dataTableName];
    while([validateTableRS next]){
        if([validateTableRS intForColumnIndex:0] == 0){
            
            NSString *createCollectedDataQuery = [NSString stringWithFormat:DATABASECMD_NEWCOLLECTEDDATA_DATABASE_CREATE,dataTableName];
            NSString *createCollectedDataGeoColumnQuery = [NSString stringWithFormat:DATABASECMD_NEWCOLLECTEDDATA_DATABASE_ADDGEOMETRYCOLUMN,dataTableName];
            NSString *createCollectedDataMedioaQuery = [NSString stringWithFormat:DATABASECMD_NEWCOLLECTEDDATA_MEDIA_DATABASE_CREATE,dataTableName];
            [dataFMDB executeUpdate:createCollectedDataQuery];
            
            FMResultSet *addGeoColumnRS = [dataFMDB executeQuery:createCollectedDataGeoColumnQuery];
            while([addGeoColumnRS next]){
                
            }
            [addGeoColumnRS close];
            [dataFMDB executeUpdate:createCollectedDataMedioaQuery];
            
        }
        
    }
    [validateTableRS close];
    
    
    //NSString *insertNewDataQuery = [NSString stringWithFormat:DATABASECMD_INSERT_NEW_COLLECTEDDATA,dataTableName];
    //NSString *newID = [[NSUUID UUID] UUIDString];
    //[newdata setIdNumber:newID];
    NSString *insertNewDataQuery = [NSString stringWithFormat:@"INSERT INTO '%@'(OBJECTID, id, name, description, time_create, time_update, user_name, user_realname, geometry) VALUES ('%@','0','%@','%@','%@','%@','%@','%@',GeomFromText('%@',4490))",dataTableName,[newdata idNumber],[newdata name],[newdata dataDescription],[[NSDate date] toFormattedString],[[NSDate date] toFormattedString],[newdata createdUserName],[newdata createdRealName],[AGSGeometryParse GeometryToWKT:newdata]];
    char *err_msg = NULL;
    sqlite3_exec([dataFMDB sqliteHandle], [insertNewDataQuery UTF8String], NULL, NULL, &err_msg);
    NSLog(@"%s",err_msg);
    
    //[dataFMDB executeUpdate:insertNewDataQuery,[[NSUUID UUID] UUIDString], [NSNumber numberWithInteger:0],[newdata name],[newdata dataDescription],[newdata createdTime],[newdata createdTime],[newdata createdUserName],[newdata createdRealName], [AGSGeometryParse GeometryToWKT:newdata]];
    
    
    for(UIImage *image in [newdata imageList]){
        NSString *imageUUID = [[NSUUID UUID] UUIDString];
        
        NSString *insertNewDataQuery = [NSString stringWithFormat:@"INSERT INTO '%@_media'(OBJECTID, media, type) VALUES ('%@','%@','%@')",dataTableName,[newdata idNumber],imageUUID,@"image"];
        [dataFMDB executeUpdate:insertNewDataQuery];
        
        NSData *imagedata=UIImageJPEGRepresentation(image,1);
        NSString *imagePath = [NSString stringWithFormat:@"/%@.jpg",imageUUID];
        [[NSFileManager defaultManager] createFileAtPath:[_appDocumentPath stringByAppendingString:imagePath] contents:imagedata attributes:nil];
    }
    
    [dataFMDB close];
    
    [_fmDB executeUpdate:@"UPDATE workset_table SET time_update = ? WHERE name = ?",[[NSDate date] toFormattedString],[currentWorkSetEntity name]];
    
    [currentWorkSetEntity setUpdateTime:[[NSDate date] toFormattedString]];
}


-(void)removeCollectedData :(NSString*)worksetName :(collectedData*)data
{

    NSString *dataDBName = [NSString stringWithFormat:@"%@.sqlite",worksetName];
    NSString* datadbpath = [_appDocumentPath stringByAppendingPathComponent:dataDBName];
    
    FMDatabase *dataFMDB = [FMDatabase databaseWithPath:datadbpath];
    [dataFMDB open];
    
    NSString *deleteDataQuery = [NSString stringWithFormat:@"DELETE FROM '%@.%@' WHERE OBJECTID = '%@'",[data mainType],[data type],[data idNumber]];
    
    [dataFMDB executeUpdate:deleteDataQuery];
    
    NSString *browseMediaDatabaseQuery = [NSString stringWithFormat:@"SELECT * FROM '%@.%@_media' where OBJECTID = '%@'",[data mainType],[data type],[data idNumber]];
    FMResultSet *browseMediaFM = [dataFMDB executeQuery:browseMediaDatabaseQuery];
    while([browseMediaFM next]){
        [[NSFileManager defaultManager] removeItemAtPath:[_appDocumentPath stringByAppendingString:[browseMediaFM stringForColumn:@"media"]] error:nil];
    }
    [browseMediaFM close];
    
    NSString *deleteDataMediaQuery = [NSString stringWithFormat:@"DELETE FROM '%@.%@_media' WHERE OBJECTID = '%@'",[data mainType],[data type],[data idNumber]];
    [dataFMDB executeUpdate:deleteDataMediaQuery];

    [dataFMDB close];
    [_fmDB executeUpdate:@"UPDATE workset_table SET time_update = ? WHERE name = ?",[[NSDate date] toFormattedString],[currentWorkSetEntity name]];
    [currentWorkSetEntity setUpdateTime:[[NSDate date] toFormattedString]];
    

}

-(void)updateCollectedData :(collectedData*)cData :(NSString*)oldName newName:(NSString*)newDataName newDescription:(NSString*)newDesc newImgArray:(NSArray*)newArray;
{                                                                    

    NSString *dataDBName = [NSString stringWithFormat:@"%@.sqlite",[currentWorkSetEntity name]];
    NSString* datadbpath = [_appDocumentPath stringByAppendingPathComponent:dataDBName];
    
    FMDatabase *dataFMDB = [FMDatabase databaseWithPath:datadbpath];
    [dataFMDB open];
    
    if(newDataName != nil && oldName != nil && newDesc != nil){
        
        NSString *updateDataQuery = [NSString stringWithFormat:@"UPDATE '%@.%@' SET name = '%@',description = '%@',time_update = '%@' WHERE OBJECTID = '%@'",[cData mainType],[cData type],newDataName,newDesc,[[NSDate date] toFormattedString],[cData idNumber]];
        [dataFMDB executeUpdate:updateDataQuery];
        
        /*
        [_fmDB executeUpdate:@"UPDATE collecteddatalist SET Dataname = ?,DataDescription = ? WHERE Dataname = ?",newDataName, newDesc, oldName];
         */
        
        int index = [currentWorkSetEntity.collectedDataList indexOfObject:cData];
        [cData setName:newDataName];
        [cData setDataDescription:newDesc];
        [currentWorkSetEntity.collectedDataList replaceObjectAtIndex:index withObject:cData];
        
        [_fmDB executeUpdate:@"UPDATE workset_table SET time_update = ? WHERE name = ?",[[NSDate date] toFormattedString],[currentWorkSetEntity name]];
        [currentWorkSetEntity setUpdateTime:[[NSDate date] toFormattedString]];
         
    }
    if(newArray != nil){
        
        
        NSString *dataTableName = [NSString stringWithFormat:@"%@.%@",[cData mainType],[cData type]];
        
        
        /*delete all image file and database records before new ones inserted*/
        NSString *browseMediaDatabaseQuery = [NSString stringWithFormat:@"SELECT * FROM '%@_media' where OBJECTID = '%@'",dataTableName,[cData idNumber]];
        FMResultSet *browseMediaFM = [dataFMDB executeQuery:browseMediaDatabaseQuery];
        while([browseMediaFM next]){
            [[NSFileManager defaultManager] removeItemAtPath:[_appDocumentPath stringByAppendingString:[browseMediaFM stringForColumn:@"media"]] error:nil];
        }
        [browseMediaFM close];
        NSString *deleteExistedMediaDatabaseQuery = [NSString stringWithFormat:@"DELETE FROM '%@_media' where OBJECTID = '%@'",dataTableName,[cData idNumber]];
        [dataFMDB executeUpdate:deleteExistedMediaDatabaseQuery];
        for(UIImage *image in newArray){
            
            NSString *imageUUID = [[NSUUID UUID] UUIDString];
            NSString *imagePath = [NSString stringWithFormat:@"/%@.jpg",imageUUID];

            /*--------------------------------------------------------------------------------------------------- */
            
            NSString *insertNewDataQuery = [NSString stringWithFormat:@"INSERT INTO '%@_media'(OBJECTID, media, type) VALUES ('%@','%@','%@')",dataTableName,[cData idNumber],imagePath,@"image"];
            [dataFMDB executeUpdate:insertNewDataQuery];
            
            NSData *imagedata=UIImageJPEGRepresentation(image, 1);
            
            [[NSFileManager defaultManager] createFileAtPath:[_appDocumentPath stringByAppendingString:imagePath] contents:imagedata attributes:nil];
        }
        int index = [currentWorkSetEntity.collectedDataList indexOfObject:cData];
        [cData setNewImageList:newArray];
        [currentWorkSetEntity.collectedDataList replaceObjectAtIndex:index withObject:cData];
        
        [_fmDB executeUpdate:@"UPDATE workset_table SET time_update = ? WHERE name = ?",[[NSDate date] toFormattedString],[currentWorkSetEntity name]];
        [currentWorkSetEntity setUpdateTime:[[NSDate date] toFormattedString]];
    }
}

-(void)updateCollectedData :(collectedData*)newdata :(AGSGeometry*)newGeometry :(NSString*)newMainType :(NSString*)newType
{
    NSString *dataDBName = [NSString stringWithFormat:@"%@.sqlite",[currentWorkSetEntity name]];
    NSString* datadbpath = [_appDocumentPath stringByAppendingPathComponent:dataDBName];
    
    FMDatabase *dataFMDB = [FMDatabase databaseWithPath:datadbpath];
    [dataFMDB open];
    
    
    NSString *updateDataQuery = [NSString stringWithFormat:@"UPDATE '%@.%@' SET geometry = GeomFromText('%@',4490) WHERE OBJECTID = '%@'",[newdata mainType],[newdata type],[AGSGeometryParse GeometryToWKT:newdata],[newdata idNumber]];
    [dataFMDB executeUpdate:updateDataQuery];
    [dataFMDB close];
    
    for(collectedData *cData in currentWorkSetEntity.collectedDataList)
    {
        if([[cData idNumber] isEqualToString:[newdata idNumber]])
        {
            [cData setGeometry:newGeometry];
            [cData setMainType:newMainType];
            [cData setType:newType];
        }
    }
    [_fmDB executeUpdate:@"UPDATE workset_table SET time_update = ? WHERE name = ?",[[NSDate date] toFormattedString],[currentWorkSetEntity name]];
    [currentWorkSetEntity setUpdateTime:[[NSDate date] toFormattedString]];
}

- (AGSGeometry*)AGSGeometryWithSpatialiteWKB_gaia:(const unsigned char*)wkb size:(size_t)size {
    
    gaiaGeomCollPtr geomptr = gaiaFromSpatiaLiteBlobWkb(wkb, size);	// for spatialite geometry
    
    if (geomptr == nil)
        return nil;
    AGSGeometry *geometry = [self AGSGeometryWithGaiaGeomColl:geomptr];
    
    gaiaFreeGeomColl(geomptr);
    
    return geometry;
}

- (AGSGeometry*)AGSGeometryWithWKB_gaia:(const unsigned char*)wkb size:(size_t)size {
    
    gaiaGeomCollPtr geomptr = gaiaFromWkb(wkb, size);	// for standard wkb, test OK
    
    if (geomptr == nil)
        return nil;
    AGSGeometry *geometry = [self AGSGeometryWithGaiaGeomColl:geomptr];
    
    gaiaFreeGeomColl(geomptr);
    
    return geometry;
}

- (AGSGeometry*)AGSGeometryWithGaiaGeomColl:(gaiaGeomCollPtr)geomptr {
    AGSGeometry *geometry = nil;
    AGSSpatialReference *spatialRef = [AGSSpatialReference spatialReferenceWithWKID:4490];
    
    double x, y;
    
    // polygon (AGSPolygon with multipolygon, holes)
    
    // parse polygon
    if (geomptr->FirstPolygon) {
        AGSMutablePolygon *polygon = [[AGSMutablePolygon alloc] initWithSpatialReference:spatialRef];
        
        gaiaPolygonPtr polygonPtr;
        gaiaRingPtr ringPtr;
        polygonPtr = geomptr->FirstPolygon;
        while (polygonPtr) {
            [polygon addRingToPolygon];
            
            // exterior ring
            ringPtr = polygonPtr->Exterior;	// exterior ring
            for (int i = 0; i < ringPtr->Points; i++) {
                gaiaGetPoint(ringPtr->Coords, i, &x, &y);
                [polygon addPointToRing:[AGSPoint pointWithX:x y:y spatialReference:nil]];	// add point
            }
            
            // interior rings
            int holes = polygonPtr->NumInteriors;
            for (int k = 0; k < holes; k++) {
                [polygon addRingToPolygon];
                
                ringPtr = polygonPtr->Interiors + k;	// interior ring
                for (int i = 0; i < ringPtr->Points; i++) {
                    gaiaGetPoint(ringPtr->Coords, i, &x, &y);
                    [polygon addPointToRing:[AGSPoint pointWithX:x y:y spatialReference:nil]];	// add point
                }
            }
            
            polygonPtr = polygonPtr->Next;
        }
        geometry = polygon;
    }
    
    // polyline (AGSPolyline with multipolyline)
    
    // parse polyline
    else if (geomptr->FirstLinestring) {
        AGSMutablePolyline *polyline = [[AGSMutablePolyline alloc] initWithSpatialReference:spatialRef];
        
        gaiaLinestringPtr polylinePtr;
        polylinePtr = geomptr->FirstLinestring;
        while (polylinePtr) {
            [polyline addPathToPolyline];
            
            for (int i = 0; i < polylinePtr->Points; i++) {
                gaiaGetPoint(polylinePtr->Coords, i, &x, &y);
                [polyline addPointToPath:[AGSPoint pointWithX:x y:y spatialReference:nil]];	// add point
            }
            
            polylinePtr = polylinePtr->Next;
        }
        geometry = polyline;
    }
    
    // point (AGSPoint or AGSMultipoint)
    
    else if (geomptr->FirstPoint) {
        int nPointPtr = 0;
        gaiaPointPtr pointPtr;
        
        pointPtr = geomptr->FirstPoint;
        while (pointPtr) {
            nPointPtr++;
            pointPtr = pointPtr->Next;
        }
        
        if (nPointPtr == 1) {
            pointPtr = geomptr->FirstPoint;
            x = pointPtr->X;
            y = pointPtr->Y;
            geometry = [AGSPoint pointWithX:x y:y spatialReference:spatialRef];
        }
        else if (nPointPtr) {
            AGSMutableMultipoint *point = [[AGSMutableMultipoint alloc] initWithSpatialReference:spatialRef];
            pointPtr = geomptr->FirstPoint;
            while (pointPtr) {
                x = pointPtr->X;
                y = pointPtr->Y;
                [point addPoint:[AGSPoint pointWithX:x y:y spatialReference:nil]];
                
                pointPtr = pointPtr->Next;
            }
            geometry = point;
        }
    }
    
    return geometry;
}
@end
